from threading import Thread, Lock

g_num = 0

lock = Lock()  # 创建锁


# 需求：采用了两个线程分别对g_num进行累加100万次

def sum_num1():
    with lock:
        for i in range(1000000):
            global g_num
            g_num += 1
    # with 语句自动释放锁，这里不需要手动释放
    # lock.release()  # 释放锁
    print(f'线程1累加之后的结果{g_num}')


def sum_num2():
    with lock: # 抢夺锁
        for i in range(1000000):
            global g_num
            g_num += 1
    # with 语句自动释放锁，这里不需要手动释放
    # lock.release()  # 释放锁
    print(f'线程2累加之后的结果{g_num}')


if __name__ == '__main__':
    t1 = Thread(target=sum_num1)
    t2 = Thread(target=sum_num2)

    t1.start()
    # t1.join()  # 主线程阻塞，变成两个线程的同步运行

    t2.start()
